package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;




    @Override
    public List<Department> loadTree() {
        //查询一级和二级部门
        List<Department> departments = departmentMapper.loadOneLevelAndTwoLevelDepartments();
        for (Department department : departments) {
            //二级部门
            List<Department> children = department.getChildren();
            //意味着一级部门是没有二级部门的
            if(children.size() == 0 ){
                department.setChildren(null);
                continue;
            }
            //把所有的二级部门丢进去，查询3级，4级。。。n级
            this.loadMultistage(children);
        }
        return departments;
    }

    /**
     * 查询多级部门的(二级下面的三级，三级下面的四级)
     * @param departments
     */
    private void loadMultistage(List<Department> departments){
        if(departments.size()!=0){
            for (Department department : departments) {
                //通过父id查询子部门
                List<Department> children = departmentMapper.loadByParentId(department.getId());
                //把查询出来的下级所有部门设置到上级部门
                department.setChildren(children.size() == 0 ? null : children);
                //把下级所有部门再次进行查询下下级
                this.loadMultistage(children);
            }
        }
    }


}
